const cp = require('child_process');
const {resolve} = require('path');
const mongoose = require('mongoose');
const Movie = mongoose.model('Movie');

;
(async () => {
    const script = resolve(__dirname, '../crawler/trailer-list.js');
    const child = cp.fork(script, []);
    let invoked = false;

    // error event 
    child.on('error', err => {
        if (invoked) return;
        invoked = true;
        console.log(err);
    })

    // exit event
    child.on('exit', code => {
        if (invoked) return;
        invoked = true;
        let err = code === 0 ? null : new Error('exit code ' + code);
        console.log(err);
    })

    // message event
    child.on('message', data => {
        let result = data.result;
        // console.log(result);
        result.forEach(async item => {
            let movie = await Movie.findOne({
                doubanId: item.doubanId
            })
            // 如果数据库不存在，就存入数据库
            if (!movie) {
                movie = new Movie(item);
                await movie.save();
            }
        });
    })
})();